package com.hxkcloud.patient.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.beans.FileUploadBean;
import com.hxkcloud.patient.beans.UpdateUserInfo;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.config.ApplicationConfig;
import com.hxkcloud.patient.dborm.LoginInfoDao;
import com.hxkcloud.patient.popup.PictureSelectPopupWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageOptionUtils;
import com.hxkcloud.patient.utils.ImageVideoUtils;
import com.hxkcloud.patient.views.CircleImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ray_lei on 2016/7/10.
 */
public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener, PictureSelectPopupWindow.FinishListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_finish;

    private CircleImageView iconView;
    private Button choosepicBtn;
    private EditText nameET;
    private EditText sexET;
    private EditText specityET;

    private PopupWindow popup_sex;//选择性别的popup
    private Button bt_male;
    private Button bt_female;
    private Button bt_cancel;

    private PictureSelectPopupWindow picSelect;

    private static final int TAKE_PHOTO_PICTURE = 1;
    private static final int TAKE_PHOTO_VIDEO = 2;
    private static final int SELECT_PICTURE = 3;
    private static final int SELECT_VIDEO = 4;
    private static final int CUT_PICTURE = 5;

//    private LoginInfo userInfo;

    private ObjectResultBean<UpdateUserInfo> resultBean;

    private List<FileUploadBean> fileResultBean;

    private Bitmap mBitmap = null;
    private String userIconPath = "";
    private String userIconUrl = "";

    private ScrollView scrollView;


    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_UPDATEUSERINFO_SUCCESS:
                dismisssLoading();
                if (msg.obj != null) {
                    resultBean = (ObjectResultBean<UpdateUserInfo>) msg.obj;
                    toastMsg(resultBean.getMessage());
                    LoginInfoDao userDao = new LoginInfoDao(mContext);
//                    LoginInfo infoBean = userDao.getUser();
//                    infoBean.setUserId(loginInfo.getUserId());
//                    infoBean.setUserStyle(loginInfo.getUserStyle());
//                    infoBean.setHeadImg(userIconUrl);
//                    infoBean.setSex(userInfo.getSex());
//                    infoBean.setName(userInfo.getName());
//                    infoBean.setSpecialty(userInfo.getSpecialty());
                    userDao.setUser(loginInfo);
                    finish();
                }

                break;
            case MessageCode.NETWORKCODE_UPDATEUSERINFO_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }
                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_SUCCESS:
                if (msg.obj != null) {
                    fileResultBean = (List<FileUploadBean>) msg.obj;
                    userIconPath = fileResultBean.get(0).getFilePath();
                    userIconUrl = fileResultBean.get(0).getUrl();
                    loginInfo.setHeadImg(userIconUrl);
                    System.out.println("fileResultBean.get(0).getFilePath()====" + fileResultBean.get(0).getFilePath());
                    iconView.setImageBitmap(mBitmap);
                }
                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.fileuploadfail));
                }
                break;

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_personalinfo);
//        userInfo = new LoginInfo();
        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_finish = (TextView) findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.persoanlinfo_text_title));
        tv_finish.setVisibility(View.VISIBLE);
        tv_finish.setText(getResources().getText(R.string.userinfo_text_finish));
        iv_back.setOnClickListener(this);
        tv_finish.setOnClickListener(this);

        nameET = (EditText) findViewById(R.id.personalinfo_et_name);
        sexET = (EditText) findViewById(R.id.personalinfo_et_sex);
        specityET = (EditText) findViewById(R.id.personalinfo_et_zhuanchang);
        iconView = (CircleImageView) findViewById(R.id.personalinfo_ci_logo);
        choosepicBtn = (Button) findViewById(R.id.personalinfo_btn_choosepic);

//        scrollView = (ScrollView) findViewById(R.id.personalinfo_sc);

        picSelect = new PictureSelectPopupWindow(this, screenWidth,
                screenHeight, this);

        initPopup();
    }

    @Override
    protected void initListener() {
        iv_back.setOnClickListener(this);
        sexET.setOnClickListener(this);
        choosepicBtn.setOnClickListener(this);
        tv_finish.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        imageLoader.displayImage(loginInfo.getHeadImg(), iconView, ImageOptionUtils.getInstance().getNurseHeadOptions());
        nameET.setText(loginInfo.getName());
        if ("0".equals(loginInfo.getSex())) {
            sexET.setText(getResources().getString(R.string.male));
        } else if ("1".equals(loginInfo.getSex())) {
            sexET.setText(getResources().getString(R.string.female));
        }
        specityET.setText(loginInfo.getSpecialty());

    }

    private void initPopup() {
        popup_sex = new PopupWindow(this);
        View viewSex = LayoutInflater.from(this).inflate(R.layout.popup_selectsex, null);
        popup_sex.setContentView(viewSex);

        popup_sex.setWidth(screenWidth);
        popup_sex.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_sex.setFocusable(true);
        popup_sex.setTouchable(true);
        popup_sex.setOutsideTouchable(true);
        popup_sex.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_sex.setAnimationStyle(R.style.popupwindow_anim_default);

        bt_male = (Button) viewSex.findViewById(R.id.bt_selectsex_male);
        bt_female = (Button) viewSex.findViewById(R.id.bt_selectsex_female);
        bt_cancel = (Button) viewSex.findViewById(R.id.bt_selectsex_cancel);

        bt_male.setOnClickListener(this);
        bt_female.setOnClickListener(this);
        bt_cancel.setOnClickListener(this);

        popup_sex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PersonalInfoActivity.this);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back://back
                finish();
                break;
            case R.id.tv_title_func:
                String name = nameET.getText().toString();
                String specity = specityET.getText().toString();
                String sex = sexET.getText().toString();
                if (getResources().getString(R.string.male).equals(sex)) {
                    loginInfo.setSex("0");
                } else /*if (getResources().getString(R.string.female).equals(sex))*/ {
                    loginInfo.setSex("1");
                }
                if (!TextUtils.isEmpty(name)) {
                    loginInfo.setName(name);
                } else {
                    loginInfo.setName("");
                }
                if (!TextUtils.isEmpty(specity)) {
                    loginInfo.setSpecialty(specity);
                } else {
                    loginInfo.setSpecialty("");
                }
                loading();
                YiJiaHuNetWorkUtils.updateUserInfo(loginInfo, handler);
                break;
            case R.id.personalinfo_et_sex:
                closeInputMethodManager();
                popup_sex.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                BrightnessUtils.lightOff(PersonalInfoActivity.this);
                break;
            case R.id.bt_selectsex_male:
                sexET.setText(getResources().getText(R.string.male));
                loginInfo.setSex("0");
                popup_sex.dismiss();
                break;
            case R.id.bt_selectsex_female:
                sexET.setText(getResources().getText(R.string.female));
                loginInfo.setSex("1");
                popup_sex.dismiss();
                break;
            case R.id.bt_selectsex_cancel:
                popup_sex.dismiss();
                break;
            case R.id.personalinfo_btn_choosepic:
                picSelect.setType(1);
                picSelect.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                break;
        }
    }

    // 上传文件的内容

    private File cameraPath;
    private File cameraFile;
    private String cameraFileName;

    @Override
    public void onFinished(int options, int type) {
        cameraPath = new File(ApplicationConfig.PicAndVideoUrl);
        if (!cameraPath.exists()) {
            cameraPath.mkdirs();
        }
        Intent mIntent;
        if (options == 1) {// 打开相机
            if (type == 1) {// 拍照
                mIntent = new Intent();
                mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                if (cameraFileName == null) cameraFileName = System.currentTimeMillis() + ".jpg";
                if (cameraFile == null) cameraFile = new File(cameraPath, cameraFileName);
                mIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(cameraFile));
                startActivityForResult(mIntent,
                        TAKE_PHOTO_PICTURE);
            }
        } else if (options == 2) {// 打开相册
            if (type == 1) {// 相册选择照片
                mIntent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                mIntent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(mIntent,
                        SELECT_PICTURE);
            }
        }

    }

    private Uri imageUri = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO_PICTURE:// 照相
                    if (resultCode == Activity.RESULT_OK) {
                        if (cameraFile != null) {
                            File outFile = new File(cameraPath, cameraFileName);
                            ImageVideoUtils.compressPicture(cameraFile, outFile);
                            imageUri = Uri.fromFile(outFile);
                            Intent intent = new Intent("com.android.camera.action.CROP");
                            intent.setDataAndType(Uri.fromFile(outFile), "image/*");
                            // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
                            intent.putExtra("crop", "true");
                            // aspectX aspectY 是宽高的比例
                            intent.putExtra("aspectX", 1);
                            intent.putExtra("aspectY", 1);
                            // outputX outputY 是裁剪图片宽高
                            //				intent.putExtra("outputX", 150);
                            //				intent.putExtra("outputY", 150);
                            intent.putExtra("return-data", false);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//文件输出路径
                            intent.putExtra("outputFormat", "JPEG"); //输入文件格式
                            startActivityForResult(intent, CUT_PICTURE);
                        }
                    }
                    break;
                case SELECT_PICTURE:// 选择照片
                    if (resultCode == Activity.RESULT_OK) {
                        if (data.getData() != null) {
                            Uri uri = data.getData();
                            if (uri != null) {
                                //创建图片保存目录

                                cameraFileName = System.currentTimeMillis() + ".jpg";
                                cameraFile = new File(cameraPath, cameraFileName);
                                imageUri = Uri.fromFile(cameraFile);
                                Intent intent = new Intent("com.android.camera.action.CROP");
                                intent.setDataAndType(uri, "image/*");
                                // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
                                intent.putExtra("crop", "true");
                                // aspectX aspectY 是宽高的比例
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                // outputX outputY 是裁剪图片宽高
//							intent.putExtra("outputX", 150);
//							intent.putExtra("outputY", 150);
                                intent.putExtra("return-data", false);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//文件输出路径
                                intent.putExtra("outputFormat", "JPEG"); //输入文件格式
                                startActivityForResult(intent, CUT_PICTURE);

                            }
                        }
                    }
                    break;
                case CUT_PICTURE://图片裁剪
                    if (imageUri != null) {
                        if (cameraFile != null) {
                            ImageVideoUtils.compressPicture(cameraFile, cameraFile);
                            System.out.println("cameraFile.getAbsolutePath()====" + cameraFile.getAbsolutePath());
                            mBitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
                            List<File> images = new ArrayList<>();
                            images.add(cameraFile);
                            YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);
                        }
                    }
                    imageUri = null;
                    break;
            }
        }


    }
}
